package dyy.zc.campuspay.ui.activity;

import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import dyy.zc.campuspay.R;
import dyy.zc.campuspay.application.MyApplication;
import dyy.zc.campuspay.base.BaseActivity;
import dyy.zc.campuspay.bean.Account;
import dyy.zc.campuspay.bean.OrderInfo;
import dyy.zc.campuspay.constant.Constants;
import dyy.zc.campuspay.utils.BmobUtils;
import dyy.zc.campuspay.utils.ImageLoaderUtils;
import dyy.zc.campuspay.utils.ToastUtils;
import dyy.zc.campuspay.views.CircleImageView;
import dyy.zc.campuspay.views.CleanableEditText;
import dyy.zc.campuspay.views.PopwindowsInput;
import dyy.zc.campuspay.views.PswInputView;

public class ZhuanZhangActivity extends BaseActivity  {

    private CircleImageView head;
    private TextView name,ok,title;
    private CleanableEditText price;
    public Account account;
    private BmobUtils bmobUtils;
    private String Price;//转账金额
    private PopwindowsInput popwindowsInput;
    public Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case Constants.ResultCode.SUCCESS:
                    if (account.getHead()!=null){
                        ImageLoaderUtils.initImage(ZhuanZhangActivity.this,
                                account.getHead().getFileUrl(), head, R.mipmap.ic_launcher);
                    }else {
                        head.setImageResource(R.mipmap.ic_launcher);
                    }
                    name.setText(account.getRealName());
                    break;
                case Constants.ResultCode.UPLOAD_SUCCESS:
                    dialog.dismiss();
                    popwindowsInput.dismiss();
                    ToastUtils.shortToast(ZhuanZhangActivity.this,"转账成功");
                    startActivity(MainActivity.class);
                    break;
            }

        }
    };
    @Override
    protected void findViewByIDS() {
        head = findViewsById(R.id.civ_head);
        name = findViewsById(R.id.tv_name);
        ok = findViewsById(R.id.tv_ok);
        price = findViewsById(R.id.tv_price);
        title = findViewsById(R.id.top_tv_title);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_zhuan_zhang);
        initData();
        bind();
    }

    private void initData() {
        popwindowsInput = new PopwindowsInput(ZhuanZhangActivity.this,inputCallBack);
        bmobUtils = new BmobUtils(this);
        title.setText("转账");
        Intent intent = getIntent();
        if (intent !=null){
            String id = intent.getStringExtra("id");
            bmobUtils.queryZhuanAccount(id);
        }
    }

    private void bind() {
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!price.getText().toString().equals("")){
                    Price = price.getText().toString();
                    if (Double.parseDouble(Price)>0){
                        if (Double.parseDouble(Price)<=Double.parseDouble(loginuser.getRemain())){
                            if (loginuser.getZhifuPassword() == null){
                                showDialog();//如果没有设置支付密码，去设置
                            }else {//弹出输入密码框
                                popwindowsInput.showAtLocation(findViewsById(R.id.activity_zhuan_zhang),Gravity.CENTER,0,0);
                            }
                        }else {
                            ToastUtils.shortToast(ZhuanZhangActivity.this,"余额不足请充值");
                        }
                    }else {
                        ToastUtils.shortToast(ZhuanZhangActivity.this,"请输入正确金额");
                    }


                }else {
                    ToastUtils.shortToast(ZhuanZhangActivity.this,"请输入转账金额");
                    //请输入转账金额
                }
            }
        });
    }

    /**
     * 如果没有设置支付密码，去设置
     */
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("支付密码");
        builder.setMessage("您还没有设置支付密码，去设置？");
        builder.setPositiveButton("去设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //startActivity(ZhifuPasswordActivity.class);
                Intent intent = new Intent(ZhuanZhangActivity.this,ZhifuPasswordActivity.class);
                startActivityForResult(intent,666);
            }
        });
        builder.setNegativeButton("否",null);
        builder.show();
    }

    /**
     * 转账处理
     * @param p
     */
    public void tranferMoney(String p){
        dialog = ProgressDialog.show(ZhuanZhangActivity.this, null, "正在转账...");
        //更新接受者的余额
        double remain = Double.parseDouble(account.getRemain())+Double.parseDouble(p);
        account.setRemain(String.valueOf(remain));
        bmobUtils.updateAccountInfo(account);
        //更新转账者的余额
        loginuser.setRemain(String.valueOf(Double.parseDouble(loginuser.getRemain())-
                Double.parseDouble(p)));
        bmobUtils.updateAccountInfo(loginuser);
        //生成订单号  唯一性
        //支付者的账单
        int r1=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r2=(int)(Math.random()*(10));
        long now = System.currentTimeMillis();//一个13位的时间戳
        String paymentID =String.valueOf(r1)+String.valueOf(r2)+String.valueOf(now);// 订单ID
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setId(loginuser.getId());
        orderInfo.setPayStyle("APP支付");
        orderInfo.setOrderNum(paymentID);
        orderInfo.setPrice(p);
        orderInfo.setType(false);
        orderInfo.setDescribe("给"+account.getNikeName()+"转账");
        bmobUtils.upLoadOrderInfo(orderInfo);

        //接受者的账单
        int r3=(int)(Math.random()*(10));//产生2个0-9的随机数
        int r4=(int)(Math.random()*(10));
        long now1 = System.currentTimeMillis();//一个13位的时间戳
        String paymentID2 =String.valueOf(r3)+String.valueOf(r4)+String.valueOf(now1);// 订单ID
        OrderInfo orderInfo1 = new OrderInfo();
        orderInfo1.setId(account.getId());
        orderInfo1.setPayStyle("APP支付");
        orderInfo1.setOrderNum(paymentID2);
        orderInfo1.setPrice(p);
        orderInfo1.setType(true);
        orderInfo1.setDescribe("收到"+loginuser.getNikeName()+"转账");
        bmobUtils.upLoadOrderInfo(orderInfo1);

        MyApplication.getInstance().saveUserInfo(loginuser);
    }

    private PswInputView.InputCallBack inputCallBack = new PswInputView.InputCallBack() {
        @Override
        public void onInputFinish(String result) {
            if (result.equals(loginuser.getZhifuPassword())){
                tranferMoney(Price);
            }else {
                ToastUtils.shortToast(ZhuanZhangActivity.this,"支付密码错误，请重新输入");
                popwindowsInput.pswInputView.clearResult();
            }
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e("requestCode",requestCode+"---"+resultCode+"----"+data+"");
        if (requestCode == 666){
            if (data != null){
                if (data.getBooleanExtra("mima",false)){
                    loginuser = MyApplication.getInstance().readLoginUser();
                }

            }
        }
    }
}
